package com.atguigu.springsecurity.service.impl;

import com.atguigu.springsecurity.entity.User;
import com.atguigu.springsecurity.mapper.MenuMapper;
import com.atguigu.springsecurity.service.UserService;
import com.atguigu.springsecurity.vo.LoginUserVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class UserDetialServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Resource
    private MenuMapper menuMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUserName, username);

        // 查询到user
        User user = userService.getOne(lambdaQueryWrapper);

        // 如果没有查询到用户就抛出异常
        if(user == null) {
            // 因为有一个ExceptionTransaltion的全局异常处理器
            // 过程中异常的信息就可以被捕获
            throw new RuntimeException("用户名或者密码错误");
        }

        // TODO 查询对应的权限信息
        // 权限信息
        List<String> list = menuMapper.selectPermsByUserId(user.getId());
        // 把数据封装成UserDetails进行返回(这里就是user信息，然后传递给登录的界面)
//        List<String> list = new ArrayList<>(Arrays.asList("test"));

        // 存入权限信息
        LoginUserVo loginUserVo = new LoginUserVo(user, list);
        // 在这里面进行密码的判断他会自动跳去密码判断
        // TODO 去authemticationProvide里面去判断密码
        return loginUserVo;
    }
}
